package com.capricorn.orion.messagebot;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

public class MySmsReceiver extends BroadcastReceiver {

	@SuppressLint("DefaultLocale")
	@Override
	public void onReceive(Context context, Intent intent) {
	    Object[] pdus=(Object[])intent.getExtras().get("pdus");
	    SmsMessage shortMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
	    SmsManager smsManager = SmsManager.getDefault();
	    String receivedMessage = shortMessage.getMessageBody();
	    if (receivedMessage != null &&
	    		receivedMessage.toLowerCase().contains("kudesi")) {
	    	String sender = shortMessage.getOriginatingAddress();
	    	Location location = getGpsCoordinates(context);
	    	String coords = 
	    			location != null ?
	    			(location.getLatitude() + "," + location.getLongitude()) :
	    			"no location :-{";
	    	smsManager.sendTextMessage(sender, null, coords, null, null);
	    }

	    Log.i("SMSReceiver","SMS message sender: "+
	       shortMessage.getOriginatingAddress());
	    Log.i("SMSReceiver","SMS message text: "+
	       shortMessage.getDisplayMessageBody());
		
	}
	private Location getGpsCoordinates(Context context) {
		// Get the location manager
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		boolean enabled = locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER);

		// Check if enabled and if not send user to the GPS settings
		// Better solution would be to display a dialog and suggesting to
		// go to the settings
		if (!enabled) {
			Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			context.startActivity(intent);
		}
		// Define the criteria how to select the location provider -> use
		// default
		Criteria criteria = new Criteria();
		String provider = locationManager.getBestProvider(criteria, false);
		return locationManager.getLastKnownLocation(provider);
	}
}
